package com.sqfw.project.utils.kms;


import com.koal.kms.sdk.ed.KmsUtil;
import com.koal.kms.sdk.ed.Mode;
import com.sqfw.project.system.domain.SysBssSign;
import com.sqfw.project.system.service.ISysBssSignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Base64;
import java.util.List;

@Slf4j
@Component
public class KmsClientUtils {


    @Autowired
    private ISysBssSignService sysBssSignService;

    /**
     *  kms数据加密， CFB模式
     * */
    public String encryptCfb(String correlationId, String originData,  String dataType) {
        log.info("关联id：{}, CFB模式-加密明文：{}", correlationId, originData);
        SysBssSign queryBssSign = new SysBssSign();
        queryBssSign.setCorrelationId(correlationId);
        queryBssSign.setDataType(dataType);
        List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(queryBssSign);
        try {
            // 数据库存储字段certAlias：ivCfb
            byte[] ivCfb = KmsUtil.generateRandom(16);
            byte[] b = KmsUtil.encrypt(originData.getBytes(), Mode.CFB, ivCfb);
            String b64SignedData = Base64.getEncoder().encodeToString(b);
            String certAlias = Base64.getEncoder().encodeToString(ivCfb);
            log.info("CFB模式加密密文（Base64编码）: {}", b64SignedData);
            // 之前没有加过密，比如添加新用户密码
            if (CollectionUtils.isEmpty(signs)) {
                SysBssSign sysBssSign = new SysBssSign(correlationId, dataType,
                        originData, null, certAlias, b64SignedData, null);
                sysBssSignService.insertSysBssSign(sysBssSign);
            }else {
                SysBssSign bssSign = signs.get(0);
                SysBssSign sysBssSign = new SysBssSign(correlationId, dataType,
                        originData, null, certAlias, b64SignedData, null);
                sysBssSign.setId(bssSign.getId());
                sysBssSign.setIsUpdate(0);
                sysBssSignService.updateSysBssSign(sysBssSign);
            }
            return b64SignedData;
        }catch (Exception e) {
            log.error("CFB模式加密错误： {}", e.getMessage());
            return null;
        }

    }

    /**
     *  kms数据加密， CFB模式
     *
     * */
//    public void encryptCbc(String correlationId, String originData,  String dataType) {
//        // 数据加密
//        log.info("CFB模式-加密明文：{}", originData);
//        // 加密方法
//        byte[] b2 = KmsUtil.encrypt(originData.getBytes(), Mode.CBC, null);
//        String be2 = Base64.getEncoder().encodeToString(b2);
//        System.out.println("CBC模式加密密文（Base64编码）："+ be2);
//
//
//    }

    // 数据解密
    public String decryptCfb(String correlationId, String originData, String dataType) {
        log.info("关联id：{}，解密数据明文：{}", correlationId, originData);
        try {
            SysBssSign sysBssSign = new SysBssSign();
            sysBssSign.setCorrelationId(correlationId);
            sysBssSign.setDataType(dataType);
            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(sysBssSign);
            if (!CollectionUtils.isEmpty(signs)) {
                SysBssSign bssSign = signs.get(0);
                if (StringUtils.isNotBlank(bssSign.getB64SignedData())) {
                    log.info("解密密文：{}", bssSign.getB64SignedData());
                    byte[] ivCfb =  Base64.getDecoder().decode(bssSign.getCertAlias());
                    byte[] bd = Base64.getDecoder().decode(bssSign.getB64SignedData());
                    byte[] b = KmsUtil.decrypt(bd, Mode.CFB, ivCfb);
                    log.info("CFB模式解密数据：{}", new String(b));
                    return  new String(b);
                }
            }
            return null;
        }catch (Exception e) {
            return null;
        }


    }

//    public String decryptCbc(String correlationId, String originData, String dataType) {
//        // 数据解密
//        log.info("解密数据明文：{}", originData);
//        try {
//            SysBssSign sysBssSign = new SysBssSign();
//            sysBssSign.setCorrelationId(correlationId);
//            sysBssSign.setDataType(dataType);
//            List<SysBssSign> signs = sysBssSignService.selectSysBssSignList(sysBssSign);
//            if (!CollectionUtils.isEmpty(signs)) {
//                SysBssSign bssSign = signs.get(0);
//                if (StringUtils.isNotBlank(bssSign.getB64OriginData())) {
//                    log.info("解密密文：{}", bssSign.getB64OriginData());
//                    byte[] bd = Base64.getDecoder().decode(bssSign.getB64OriginData());
//                    byte[] b = KmsUtil.decrypt(bd, Mode.CBC, null);
//                    String data = Base64.getEncoder().encodeToString(b);
//                    log.info("CBC模式解密数据：{}", new String(b));
//                    return data;
//                }
//            }
//            return null;
//        }catch (Exception e) {
//            return null;
//        }
//
//    }

}
